package com.sun.servlet;

import com.alibaba.fastjson.JSON;
import com.sun.entity.Movie;
import com.sun.service.MovieService;
import com.sun.service.impl.MovieServiceImpl;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

@WebServlet(urlPatterns = "/MovieServlet.action")
public class MovieServlet extends HttpServlet {
    MovieService movieService = new MovieServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opr = req.getParameter("opr");
        String jsonString = null;//用来存转换的json数据
        String str = "no";//用来存储返回的值
        switch (opr){
            case "selectMovie" :
                int page = Integer.parseInt(req.getParameter("page"));
                List<Movie> movieList = movieService.selectMovie(page);
                jsonString = JSON.toJSONString(movieList);
                resp.getWriter().write(jsonString);
                break;
            case "selectAllNumber" :
                int num = movieService.selectAllNumber();
                jsonString = JSON.toJSONString(num);
                resp.getWriter().write(jsonString);
                break;
            case "selectMovieByMovieName" :
                if (movieService.selectMovieByMovieName(req.getParameter("movieName"))>0){
                    str = "ok";
                }
                jsonString = JSON.toJSONString(str);
                resp.getWriter().write(jsonString);
                break;
            case "addMovie" :
                Movie movie = new Movie();
                movie.setMovieName(req.getParameter("movieName"));
                movie.setMovieType(req.getParameter("movieType"));
                movie.setPrice(Float.parseFloat(req.getParameter("price")));
                movie.setRecommend(Integer.parseInt(req.getParameter("recommend")));
                movie.setVotes(Integer.parseInt(req.getParameter("votes")));
                try{
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    movie.setStartTime(sdf.parse(req.getParameter("startTime")));
                    movie.setEndTime(sdf.parse(req.getParameter("endTime")));
                }catch (Exception e){
                    e.printStackTrace();
                }
                if (movieService.addMovie(movie)>0){
                    str = "ok";
                }
                jsonString = JSON.toJSONString(str);
                resp.getWriter().write(jsonString);
                break;
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }

}
